package com.saasitems.admin.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.saasitems.admin.dao.MediaResMapper;
import com.saasitems.admin.dao.ProductExtMapper;
import com.saasitems.admin.dao.ProductMapper;
import com.saasitems.admin.model.*;
import com.saasitems.admin.web.vo.product.ProductQueryVO;
import com.saasitems.admin.web.vo.product.ProductVO;
import com.saasitems.admin.web.vo.product.UpFiles;
import com.saasitems.common.model.PageInfo;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2016/12/26.
 */
@Service
public class ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private MediaResMapper mediaResMapper;

    @Autowired
    private ProductExtMapper productExtMapper;

    /**
     *
     * @param vo
     * @param
     */
    public void insert(Product vo, UpFiles fs) {
        productMapper.insert(vo);

        if (fs == null)
            return;
        if (fs.getFileName() == null)
            return;

        for (int i = 0; i < fs.getFileName().length; i++) {
            MediaRes mr = new MediaRes();
            mr.setFileName(fs.getFileName()[i]);
            mr.setFileSize(100);
            mr.setUpdDateTime(new Date());
            mr.setUpdUserId(105L);
            this.mediaResMapper.insert(mr);

            ProductExt pe = new ProductExt();
            pe.setMdResId(mr.getId());
            pe.setProductId(vo.getId());
            productExtMapper.insert(pe);
        }
//        JSONArray array = JSONArray.fromObject(jsonPics);
//        for (int i = 0; i < array.size(); i++) {
//            JSONObject ob = array.getJSONObject(i);
//            MediaRes mr = new MediaRes();
//
//            if (ob.containsKey("fileName")) {
//                mr.setFileName(ob.getString("fileName"));
//            }
//            if (ob.containsKey("fileSize")) {
//                mr.setFileSize(100);
//            }
//
//            mr.setUpdDateTime(new Date());
//            mr.setUpdUserId(105L);
//            this.mediaResMapper.insert(mr);
//
//            ProductExt pe = new ProductExt();
//            pe.setMdResId(mr.getId());
//            pe.setProductId(vo.getId());
//            productExtMapper.insert(pe);
//        }
    }

//    public List<ProductVO> query() {
//        ProductExample ex = new ProductExample();
//        ex.createCriteria();
//        List<ProductVO> ret = new ArrayList<ProductVO>();
//        List<Product> list = this.productMapper.selectByExample(ex);
//
//        for (Product p : list) {
//            ProductVO vo = new ProductVO();
//            BeanUtils.copyProperties(p, vo);
//            ret.add(vo);
//        }
//        return ret;
//    }

    public List<ProductVO> query(ProductQueryVO queryVO, PageInfo page) {
        ProductExample ex = new ProductExample();
        ProductExample.Criteria c = ex.createCriteria();
        if (queryVO != null) {
            if (StringUtils.isNotBlank(queryVO.getSn())) {
                c.andSnEqualTo(queryVO.getSn());
            }
            if (StringUtils.isNotBlank(queryVO.getName())) {
                c.andSnEqualTo(queryVO.getName());
            }
            if (queryVO.getTimeStart() != null) {
                c.andCreDateTimeGreaterThanOrEqualTo(queryVO.getTimeStart());
            }
            if (queryVO.getTimeEnd() != null) {
                c.andCreDateTimeLessThanOrEqualTo(queryVO.getTimeEnd());
            }
        }

        if (page != null) {
            PageHelper.startPage(page.getPageNo(), page.getPageSize());
        }
        List<ProductVO> ret = new ArrayList<ProductVO>();
        List<Product> list = this.productMapper.selectByExample(ex);
        if (page != null) {
            // 取count的值
            page.setTotalCount((long)((Page) list).getTotal());
        }
        for (Product p : list) {
            ProductVO vo = new ProductVO();
            BeanUtils.copyProperties(p, vo);
            ret.add(vo);
        }
        return ret;
    }

    /**
     * 通过主键获得产品信息
     * @param id
     * @return
     */
    public ProductVO getInfoById(Long id) {
        Product p = productMapper.selectByPrimaryKey(id);
        ProductVO vo = new ProductVO();
        BeanUtils.copyProperties(p, vo);
        return vo;
    }

    /**
     * 根据产品id获取上传文件列表
     * @param id
     * @return
     */
    public UpFiles getFilesByProductId(Long id) {
        UpFiles ups = null;
        ProductExtExample ex = new ProductExtExample();
        ex.createCriteria().andProductIdEqualTo(id);
        List<ProductExt> list = productExtMapper.selectByExample(ex);

        List<Long> fileIds = new ArrayList<Long>();
        for (ProductExt pe : list) {
            fileIds.add(pe.getMdResId());
        }
        if (fileIds.isEmpty()) {
            return ups;
        }

        MediaResExample mrex = new MediaResExample();
        mrex.createCriteria().andIdIn(fileIds);
        List<MediaRes> mrlist = mediaResMapper.selectByExample(mrex);
        if (mrlist != null && !mrlist.isEmpty()) {
            int len = mrlist.size();
            for (int i = 0; i < mrlist.size(); i++) {
                MediaRes mr = mrlist.get(i);
                if (ups == null) {
                    ups = new UpFiles();
                    ups.setFileId(new String[len]);
                    ups.setFileName(new String[len]);
                    ups.setFileSize(new String[len]);
                }

                ups.getFileId()[i] = String.valueOf(mr.getId());
                ups.getFileName()[i] = mr.getFileName();
                ups.getFileSize()[i] = String.valueOf(mr.getFileSize());
//            UpFiles upFiles = new UpFiles();
//            upFiles.setFileSize(mr.getFileSize());
//            upFiles.setFileName();
            }
        }
        return ups;
    }

    /**
     *
     * @param vo
     * @param
     */
    public void update(Product vo, UpFiles fs) {
        Product oldVo = productMapper.selectByPrimaryKey(vo.getId());
        vo.setCreUserId(oldVo.getCreUserId());
        vo.setCreDateTime(oldVo.getCreDateTime());
        // 按主键更新
        productMapper.updateByPrimaryKey(vo);

        if (fs == null)
            return;
        if (fs.getFileName() == null)
            return;

        // 对应产品id的值删除
        ProductExtExample deleteEx = new ProductExtExample();
        deleteEx.createCriteria().andProductIdEqualTo(vo.getId());
        productExtMapper.deleteByExample(deleteEx);

        for (int i = 0; i < fs.getFileName().length; i++) {
            Long mrid = 0L;
            if (StringUtils.isBlank(fs.getFileId()[i])) {
                MediaRes mr = new MediaRes();
                mr.setFileName(fs.getFileName()[i]);
                mr.setFileSize(Integer.parseInt(fs.getFileSize()[i]));
                mr.setUpdDateTime(new Date());
                mr.setUpdUserId(105L);
                this.mediaResMapper.insert(mr);
                mrid = mr.getId();
            } else {
                mrid = Long.parseLong(fs.getFileId()[i]);
            }

            ProductExt pe = new ProductExt();
            pe.setMdResId(mrid);
            pe.setProductId(vo.getId());
            productExtMapper.insert(pe);
        }
    }

}
